import { getCommTreeByXid, s_getcommontableinfo, s_getcommontableinfoBycondition, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { getSelection } from "@/services/selections";
import { ActionType, ProCard, ProColumns, ProColumnType, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Col, message, Modal, Row, Space, Steps, Tabs, TabsProps, Tag, Tree, TreeNodeProps } from "antd"
import { DataNode } from "antd/es/tree";
import moment from "moment";
import { useRef, useState } from "react";



const App:React.FC=()=>{
   const [treeData,setTreeData]=useState();
   const [selectNode,setSelectNode]=useState<DataNode>();
   const [selectCategoryID,setSelectCategoryID]=useState<any[]>([]);
   const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);
   const [selectedRowId,setSelectedRowId]=useState([]);
   const [queryCondition,setQueryCondition]=useState({type:2});

   const [sampleItems,setSampleItems]=useState<{title:string,description:string,content:any}[]>([{title:'请选择样品流程',description:'请选择样品流程',content:<></>}]);
  
   const [orgSelectOptions,setOrgSelectOptions]=useState([]);
   const [personSelecOptions,setPersonSelectOptions]=useState([]);
   const [vendorSelectOptions,setVendorSelectOptions]=useState([]);
   const [vcdocumentSelectOptions,setVcdocumentSelectOptions]=useState([]);
   const [sampleProgressSelectOptions,setSampleProgressSelectOptions]=useState([]);
   const [sampleCategorySelectOptions,setSampleCategorySelectOptions]=useState([]);

   const [open,setOpen]=useState(false);
   const [etype,setEtype]=useState(1);
   const [current,setCurrent]=useState(0);
   const [formProgressId,setFormProgressId]=useState(0);
   

   const mtable_ref=useRef<ActionType>();
   const mform_ref=useRef<ProFormInstance>();
   const stable_ref=useRef<ActionType>();

   const form_progress=useRef<ProFormInstance>();

   const form_step2=useRef<ProFormInstance>();
   const form_step3=useRef<ProFormInstance>();
   const form_step4=useRef<ProFormInstance>();
   const form_step5=useRef<ProFormInstance>();
   const form_step6=useRef<ProFormInstance>();

    

   
   useRequest(()=>getCommTreeByXid({x_id:1,source_table:'base_sample_category'}),{  
      onSuccess:(data)=>setTreeData(data),
    });

    useRequest(()=>getSelection({source:'base_organization',x_id:1}),{
       onSuccess:(data)=>{
         var x=data.map((item:any)=>({value:item.id,label:item.name}));
         setOrgSelectOptions(x);
       }
    });

    useRequest(()=>getSelection({source:'base_person',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        setPersonSelectOptions(x);
      }
   });

   useRequest(()=>getSelection({source:'base_sample_progress',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        x.push({value:0,label:'请选择'});
        setSampleProgressSelectOptions(x);
      }
   });

   useRequest(()=>getSelection({source:'base_sample_category',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        setSampleCategorySelectOptions(x);
      }
   });

   useRequest(()=>getSelection({source:'vcdocument',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        setVcdocumentSelectOptions(x);
      }
   });

   useRequest(()=>getSelection({source:'v_vendor',x_id:1}),{
      onSuccess:(data)=>{
        var x=data.map((item:any)=>({value:item.id,label:item.name}));
        setVendorSelectOptions(x);
      }
   });

   //  样品申请表主表单字段
   //   operate_time,status,enddate,
   //  org_id,operater_id,sample_category_id,
   //  business_id,sample_progress_id,source_xid,x_id,id,
   //  vendor_vcid,custom_vcid,
   //  description,order_code,memo
   //附件……
    
    const step1_tab1=<><ProForm formRef={mform_ref} submitter={false}
                      initialValues={etype==0?{
                        ...selectedRecord[0],
                        operate_time:moment().format('YYYY-MM-DD'),}
                      :{
                         operate_time:moment().format('YYYY-MM-DD'),
                         status:1,
                         sample_progress_id:formProgressId,
                       }}
                        style={{height:520}}

                    >
                  <Row gutter={8}>
                     <Col span={6}>
                     {JSON.stringify(formProgressId)}
                     <ProFormSelect name='sample_progress_id' label='样品流程' 
                            request={async ()=>sampleProgressSelectOptions}
                        /> 
           
                        <ProFormSelect name='org_id' label='申请部门' 
                            request={async ()=>orgSelectOptions}
                        /> 
                        <ProFormSelect name='operater_id' label='申请人' 
                           request={async ()=>personSelecOptions}
                         /> 
                        <ProFormSelect name='x_id' label='组织ID' hidden={true} /> 
                        <ProFormText name='id' label='单据ID' hidden={true}  /> 
                     </Col>
                     <Col span={6}>
                         <ProFormText name='code' label='样品编号' /> 
                         
                         
                         <ProFormSelect name='sample_category_id' label='样品分类'
                           request={async ()=>sampleCategorySelectOptions}
                         /> 
                         <ProFormText name='order_code' label='订单号' /> 
                         
                        
                         
                     </Col>
                     <Col span={6}>
                         <ProFormText name='name' label='样品名称' />
                         <ProFormSelect name='to_xid' label='制样供应商'  
                            request={async ()=>vendorSelectOptions}
                         /> 
                         <ProFormSelect name='vendor_vcid' label='专用供应商' 
                            request={async ()=>vcdocumentSelectOptions}
                         /> 
                         
                         <ProFormSelect name='source_xid' label='来源组织' hidden={true} /> 
                         
                         
                         <ProFormSelect name='business_id' label='业务员' 
                             request={async ()=>personSelecOptions}
                         /> 
                         
                     </Col>
                     <Col span={6}>
                     <ProFormDatePicker name='enddate' label='需求时间' /> 
                     <ProFormSelect name='custom_vcid' label='专用客户' 
                       request={async ()=>vcdocumentSelectOptions}
                     /> 
                          <ProFormDatePicker name='operate_time' label='操作时间' /> 
                          
                          <ProFormRadio.Group name='status' label='状态'
                             options={[{value:1,label:'进行中'},{value:2,label:'冻结'},{value:3,label:'删除'}]}
                          />
                     </Col>
                  </Row>
                   
                     <ProFormText name='memo' label='备注' /> 
                 
                  <ProFormTextArea name='description' label='样品具体要求' /> 
                 </ProForm></>;
    
    const step1_tab2=<><ProForm submitter={false} style={{height:520}} >
                             <Button>上传附件(图像或PDF)</Button>
                        </ProForm></>;

    const step1_item:TabsProps["items"]=[
      {
         label: '样品明细',
         children: <>{step1_tab1}</>,
         key: "tab1",
      },{
         key:"tab2",
         label:'样品申请附件',
         children:<>{step1_tab2}</>
      }
    ];

    //生成样品流程表单
   async function setSampleForm(progress_id:number){
       var items:any[]=[];
       alert("progress_id:"+progress_id);
       alert(JSON.stringify(selectedRecord[0]));
       alert(JSON.stringify("etype:"+etype));
      //  setFormProgressId(progress_id);
       //新增时仅显示首表单
       if(progress_id==0){
           items.push({title:"新增打样申请",description:"请选择打样流程",
                  content:<><Tabs items={step1_item} type="card" /></>
              });
           setSampleItems(items);
       }
       //当选择样品流程后，重新生成流程和表单
       if(progress_id!=0){
         items=[];
        const x=await s_getcommontableinfoBycondition({x_id:1,source:'v_sample_progress',tdata:{id:progress_id}});
         // alert(JSON.stringify(x.data[0]));
         x.data[0].map((item:any)=>{
                  if(item.step1!=null)
                     items.push({title:item.step1,description:item.step1_description,
                                  content:<><Tabs items={step1_item} type="card" /></>
                                });

                  if(item.step2!=null)
                     items.push({title:item.step2,description:item.step2_description,
                                content:<>
                                    <ProForm submitter={false} style={{height:576}} formRef={form_step2} >
                                         <Button>上传图纸设计附件(图像或PDF)</Button>
                                         <ProFormTextArea name='step2_opinion' label='审批意见'/> 
                                    </ProForm></>
                      }) 
                  else {
                         setSampleItems(items);
                         return;
                      };
                   if(item.step3!=null)
                        items.push({title:item.step3,description:item.step3_description,
                                   content:<>
                                       <ProForm submitter={false} style={{height:576}} formRef={form_step3} >
                                            <Button>上传图纸设计附件(图像或PDF)</Button>
                                            <ProFormTextArea name='step3_opinion' label='审批意见'/> 
                                       </ProForm></>
                         }) 
                     else {
                        setSampleItems(items);
                        return;
                         };   
                     if(item.step4!=null)
                           items.push({title:item.step4,description:item.step4_description,
                                      content:<>
                                          <ProForm submitter={false} style={{height:576}} formRef={form_step4} >
                                               <Button>上传图纸设计附件(图像或PDF)</Button>
                                               <ProFormTextArea name='step4_opinion' label='审批意见'/> 
                                          </ProForm></>
                            }) 
                        else {
                           setSampleItems(items);
                           return;
                        }; 
                     if(item.step5!=null)
                              items.push({title:item.step5,description:item.step5_description,
                                         content:<>
                                             <ProForm submitter={false} style={{height:576}} formRef={form_step5} >
                                                  <Button>上传图纸设计附件(图像或PDF)</Button>
                                                  <ProFormTextArea name='step5_opinion' label='审批意见'/> 
                                             </ProForm></>
                               }) 
                           else {
                              setSampleItems(items);
                              return;
                           };
                      if(item.step6!=null)
                                 items.push({title:item.step6,description:item.step6_description,
                                            content:<>
                                                <ProForm submitter={false} style={{height:576}} formRef={form_step6} >
                                                     <Button>上传图纸设计附件(图像或PDF)</Button>
                                                     <ProFormTextArea name='step6_opinion' label='审批意见'/> 
                                                </ProForm></>
                                  }) 
                              else {
                                 setSampleItems(items);
                                 return;
                              };
                   
              });
          
            }
            //   alert(etype);
            //   setOpen(true);
            
            //   mform_ref.current?.setFieldsValue({...selectedRecord[0]});
            }

     const onChange=(value:number)=>{
        setCurrent(value);
     }             

     const onModalClose=()=>{
         setFormProgressId(0);
         setSampleItems([{title:'请选择样品流程',description:'请选择样品流程',content:<></>}]);
         setSelectedRecord([]);
         mtable_ref.current?.reloadAndRest?.();
         // setEtype(1);
         setOpen(false);
     };
   
    //点击左侧树
    function selectTreeNode(node:DataNode){
      setSelectNode(node);
      // alert(JSON.stringify(node));
      arr=[];//先置为空，再取数据
      arr.push(node.key);
      getNodeKeys(node);
      setSelectCategoryID(arr.filter((item)=>item!=null));
      
      mtable_ref.current?.reloadAndRest?.();
    }

   //  新增
   function add(){
      if(selectCategoryID.length==0)
         message.warning('请先选择类别');
      else{
         setEtype(1);
         // setOpen(true);
         setFormProgressId(0);
         // mtable_ref.current?.reset?.();
         setSelectedRecord([]);
          setSampleForm(0);
          setOpen(true);
      }
   }
    //  审核
    function verify(){
      if(selectedRecord.length==0)
         message.warning('请先要审核的行');
      else{
         setEtype(0);
         
         setFormProgressId(selectedRecord[0].sample_progress_id);
         // setOpen(true);
         setSampleForm(selectedRecord[0].sample_progress_id);
          
         // mform_ref.current?.setFieldsValue({...selectedRecord[0]});
         setOpen(true);
      }
   }
    
   async function saveInfo(n:number){
        // n为1评审通过，2为退回上一级。
       var fdata=({custom_category_id:selectNode?.key,vc_id:selectedRowId});
      //  alert(JSON.stringify(fdata));
       const x=await s_updateInfo({x_id:1,operater_id:1,source:'pur_sample',etype:1,fdata});
       if(x.success){
          message.success('保存成功');
          setOpen(false);
         //  setEtype(1);
          mtable_ref.current?.reloadAndRest?.();
       }else
          message.error('保存失败，请联系管理员');
   }

   //  操作
   async function operateInfo(n:number){
      // source,x_id,operater_id,otype,id
      if(selectedRecord.length==0)
         message.warning('请选择要操作的行');
      else{
       const x=await s_operateInfo({x_id:1,source:'sample',operater_id:1,otype:n,id:selectedRecord[0].id});
       if(x.success){
         message.success('操作成功');
         mtable_ref.current?.reloadAndRest?.();
       }else
         message.error('操作错误，请联系管理员。');
      }
   }

   async function query(){
      const fdata={...mform_ref.current?.getFieldsValue(),type:2};//1供应商2客户
      // alert(JSON.stringify(fdata));
      setQueryCondition(fdata);
      stable_ref.current?.reloadAndRest?.();
   }
    
  //--生成本级和下级的分类ID数组---先取本节点及下级节点值，再共同选
      var arr:any[]=[];
       //定义一个递归函数，获取选中节点下的所有key
      //  function getNodeKeys(node:{key:any,title:any,children:any[]}){
         function getNodeKeys(node:any){
            if(node.children.length>0)
                  node.children.map((item:any)=>{
                     arr.push(item.key);
                     if(item.children.length>0){
                          arr.push(getNodeKeys(item));
                     }
                 });
          }
      
          interface DataType{
            //  id,code,name,org_id,operater_id,sample_category_id,sample_category_name,operate_time,description,
            //  order_code,business_id,sample_progress_id,memo,vendor_vcid,status,enddate,custom_vcid,org_name,
            //  operater_name,business_name,sample_progress_name,custom_name,vendor_name
            id:number,code:string,name:string,org_id:number,operater_id:number,sample_category_id:number,
            sample_category_name:string,operate_time:string,description:string,
             order_code:string,business_id:number,sample_progress_id:number,memo:string,vendor_vcid:number,status:number,
             enddate:string,custom_vcid:number,org_name:string,
             operater_name:string,business_name:string,sample_progress_name:string,custom_name:string,vendor_name:string,
          }

          
          const columns:ProColumns<DataType>[]=[
            //  ,,,,,,,,,
            //  ,,,,, ,,,,
            //  ,,,,
            {dataIndex:'id',hidden:true},{dataIndex:'org_id',hidden:true},{dataIndex:'operater_id',hidden:true},
            {dataIndex:'sample_category_id',hidden:true},{dataIndex:'business_id',hidden:true},{dataIndex:'sample_progress_id',hidden:true},
            {dataIndex:'custom_vcid',hidden:true},{dataIndex:'vendor_vcid',hidden:true},{dataIndex:'sample_progress_name',hidden:true},
            {dataIndex:'org_name',title:'申请部门'},{dataIndex:'sample_category_name',title:'样品分类'},{dataIndex:'code',title:'样品编号'},
            {dataIndex:'name',title:'样品名'},{dataIndex:'description',title:'具体需求',width:'10%'},
            {dataIndex:'enddate',title:'要求完成日期',
               render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
            },
            {dataIndex:'order_code',title:'订单号'},{dataIndex:'custom_name',title:'客户'},{dataIndex:'vendor_name',title:'供应商'},
            {dataIndex:'business_name',title:'业务员'},{dataIndex:'memo',title:'备注'},
            {dataIndex:'operater_name',title:'申请人'},
            {dataIndex:'operate_time',title:'申请日期',
               render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
            },
            {dataIndex:'status',title:'状态',fixed:'right',width:80,
               render:(text)=>{
                  switch(text){
                     case 1: return <Tag >进行中</Tag>;break;
                     case 2: return <Tag color="blue" >冻结</Tag>;break;
                     case 3: return <Tag  color="red">删除</Tag>;break;
                     case 4: return <Tag >已完结</Tag>;break;
                  }
               }
            }, 
          ];

     return (
        <Row gutter={8}>
         <Col span={6}  >
           <ProCard title='样品分类' style={{height:700}}>
               {/* {JSON.stringify(selectCategoryID)} */}
               <Tree treeData={treeData} defaultExpandAll blockNode onClick={(e,node)=>selectTreeNode(node)} />
           </ProCard>  
         </Col>
         <Col span={18}  >
           <ProCard title='样品单' style={{height:700}} 
            extra={<Space>
                    <Button onClick={()=>add()}>新增</Button>
                    <Button onClick={()=>verify()}>审核</Button>
                    <Button onClick={()=>operateInfo(2)}>冻结</Button>
                    <Button onClick={()=>operateInfo(3)}>删除</Button>
                    <Button onClick={()=>operateInfo(1)}>恢复</Button>
                    

            </Space>}
           >
            {JSON.stringify(selectedRecord)}
               <ProTable<DataType> 
                   actionRef={mtable_ref}
                   columns={columns}
                   rowKey='id'
                   rowSelection={{
                     type:'radio',
                     // onSelect:(selectedRows:any,selectedRowKeys)=>setSelectedRecord(selectedRows),
                     onSelect:(record,selected,selectedRows)=>{
                     // onSelect:(selectedRowKeys:any, selectedRows, info)=>{
                        setSelectedRecord(selectedRows);
                        // setSampleForm(selectedRowKeys[0]);
                        // alert(JSON.stringify(selectedRows));
                        // setEtype(0);
                        setFormProgressId(selectedRows[0].sample_progress_id);
                     },
                     fixed:'left',
                   }}
                   pagination={{
                     pageSize:10,
                     showQuickJumper:true,
                   }}
                   request={async ()=>{
                     // x_id,cate_id,id,source
                     const x=await s_getcommontableinfo({x_id:1,source:'v_sample',id:0,cate_id:selectCategoryID});
                     return{
                        data:x.data[0],
                        success:true,
                     }
                   }}
                   scroll={{x:'200%'}}
                   search={false}
                />

           </ProCard>
         </Col>
          
        <Modal open={open} destroyOnClose closable okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
                   onCancel={()=>onModalClose()} onClose={()=>onModalClose()} width={'80%'}  
                >
                   <Steps items={sampleItems} current={current} type="navigation" onChange={onChange} />
                     <ProCard title='样品过程管理' 
                         extra={<Space>
                              <Button hidden={current!==0?true:false} onClick={()=>alert("etype:"+etype)}>保存</Button>
                              <Button hidden={current!=0?true:false}>下达至供应商</Button>
                              <Button hidden={current!=0?true:false}>撤回</Button>
                              <Button onClick={()=>saveInfo(1)} hidden={current==0?true:false}>评审通过</Button>
                              <Button onClick={()=>saveInfo(2)} hidden={current==0?true:false}>退回上一级</Button>
                        </Space>}
                     >
                        <ProForm formRef={form_progress} submitter={false}
                              initialValues={{sample_progress_id:formProgressId}}
                              >
                                  <ProFormSelect name='sample_progress_id' label='样品流程' style={{width:200}}
                                           request={async ()=>sampleProgressSelectOptions}
                                           onChange={(value:any)=>{
                                               setFormProgressId(value);
                                               setSampleForm(value);
                                             //   alert(formProgressId);
                                               mform_ref.current?.setFieldValue("sample_progress_id",value);
                                             //   alert(JSON.stringify(mform_ref.current?.getFieldValue("sample_progress_id")));
                                          }}
                                   /> 
                        </ProForm>
                        {etype}
                        {sampleItems[current].content}
                     </ProCard>
                </Modal>
        </Row>
     );
}
 

export default App;